package bfa.cps;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import net.moraleboost.streamscraper.ScrapeException;
import net.moraleboost.streamscraper.Scraper;
import net.moraleboost.streamscraper.Stream;
import net.moraleboost.streamscraper.scraper.ShoutCastScraper;

public class SongListChecker implements Runnable {

	private String radioLocation=null;
	private String marci=null;
	
	private long times[]={60000,30000,15000};
	//private long times[]={10000,5000,5000};
	private int timePos=times.length;
	
	public boolean keepOn=true;
	private boolean permitWork=true;
	private long timeToSleep=times[0];
	
	public Drawable image=null;
	
	@Override
	public void run() {
		while (keepOn) {
			if (isPermitWork()) {
				if (radioLocation!=null) {
					doIt(radioLocation);				
				}				
			}
			
        	if (! lastNewAll.equals(newAll)) {
        		timePos=0;
        		
        		// Song changed
        		
        		Document doc;
    			try {
    				if (getMarci()!=null) {
	    				doc = Jsoup.connect(getMarci()+"?c=custom_skin_3").get();
	    	        	setImageUrl(doc.title());
	    	
	    	        	
	    	        	Elements newsHeadlines = doc.select("#letterbox1 img");
	    	        	if (! newsHeadlines.isEmpty()) {
	        	        	Element i=newsHeadlines.get(0);
	        	        	String src=i.attr("src");
	        	        	if (! src.startsWith("http")) {
	        	        		src=getMarci()+i.attr("src");
	        	        	}
	        	        	
	        	        	setImageUrl(src);
	        	        	
	        	        	String u=getImageUrl();
	        	        	u=u.replaceAll(" ", "%20");
	        	        	
	        	        	mandaMessaggio("copertina",u);
	        	        	//InputStream URLcontent = (InputStream) new URL(getImageUrl()).getContent();
	        	        	//image = Drawable.createFromStream(URLcontent, "copertina");	        	        	
	    	        	}
	    	        	
	    	        	newsHeadlines = doc.select("#block1 p.title");
	    	        	if (! newsHeadlines.isEmpty()) {
	    	        		Element i=newsHeadlines.get(0);
	    	        		String u=  i.text().replaceAll("&amp;", "&");
	    	        		setNewSong(u);
	    	        		mandaMessaggio("song",u);
	    	        	}

	    	        	String artistAndAlbum="";
	    	        	newsHeadlines = doc.select("#block1 p.artist");
	    	        	if (! newsHeadlines.isEmpty()) {
	    	        		Element i=newsHeadlines.get(0);
	    	        		String u=i.text().replaceAll("&amp;", "&");
//	    	        		mandaMessaggio("artist",u);
	    	        		artistAndAlbum+=u;
	    	        	}

	    	        	newsHeadlines = doc.select("#block1 p.album");
	    	        	if (! newsHeadlines.isEmpty()) {
	    	        		Element i=newsHeadlines.get(0);
	    	        		String u=i.html().replaceAll("&amp;", "&");
	    	        		if (! artistAndAlbum.equals("")) {
		    	        		artistAndAlbum+=" - ";	    	        			
	    	        		}
	    	        		artistAndAlbum+=u;
//	    	        		mandaMessaggio("album",u);
	    	        	}
    	        		if (! artistAndAlbum.equals("")) {
    	        			setNewTitle(artistAndAlbum);
    	        			mandaMessaggio("title",artistAndAlbum);
    	        		}
    				}
    			} catch (IOException e1) {
    				e1.printStackTrace();
    			}            	
        	} else {
        		if (timePos<times.length-1) {
        			timePos++;
        		}
        	}

    		if (timePos>=times.length) {
    			timePos=0;
    		}
        	timeToSleep=times[timePos];
			
        	lastNewAll=newAll;
        	
        	
        	try {
    			Thread.sleep(timeToSleep);
    		} catch (InterruptedException e) {
    			e.printStackTrace();
    		}	
		}
	}
	
	private String newSong="";
	private String newTitle="";	

	private String newAll="";
	private String lastNewAll="";

	private String imageUrl="";

	
    public String doIt(String url) {
    	//Scraper scraper = new IceCastScraper();
    	Scraper scraper = new ShoutCastScraper();
        
        List<Stream> streams;
		try {
			streams = scraper.scrape(new URI(url));
	        for (Stream stream: streams) {
	            //System.out.println("Song Title: " + stream.getCurrentSong());
	            //System.out.println("URI: " + stream.getUri());
	            
//	        	Log.i("Description", "" + stream.getDescription());
//	        	Log.i("Type", "" + stream.getContentType());
	        	
//	        	setNewSong(stream.getCurrentSong().toString());
//	        	setNewTitle(stream.getTitle());
	        	
	        	newAll=stream.getCurrentSong().toString()+stream.getTitle();
	        	
//	        	mandaMessaggio("song",getNewSong());
//	        	mandaMessaggio("title",getNewTitle());
	        	
	            return stream.getCurrentSong().toString()+" - "+stream.getTitle();
	            
	            
	        }
		} catch (ScrapeException e) {
			e.printStackTrace();
		} catch (URISyntaxException e) {
			e.printStackTrace();
		}
    	
		return "?";
		
    }


	public String getRadioLocation() {
		return radioLocation;
	}


	public void setRadioLocation(String radioLocation) {
		this.radioLocation = radioLocation;
	}

	public Handler handler=null;
	Bundle b = new Bundle();
	private void mandaMessaggio(String key,String valore) {
		if (handler!=null) {	
		    Message msg = handler.obtainMessage();
		    b.clear();
		    b.putString(key,valore);
		    msg.setData(b);
		    handler.sendMessage(msg);
		 }
	}


	public String getNewSong() {
		return newSong;
	}


	public void setNewSong(String newSong) {
		this.newSong = newSong;
	}


	public String getNewTitle() {
		return newTitle;
	}


	public void setNewTitle(String newTitle) {
		this.newTitle = newTitle;
	}


	/**
	 * @return the marci
	 */
	private String getMarci() {
		return marci;
	}


	/**
	 * @param marci the marci to set
	 */
	public void setMarci(String marci) {
		this.marci = marci;
	}


	/**
	 * @return the imageUrl
	 */
	public String getImageUrl() {
		return imageUrl;
	}


	/**
	 * @param imageUrl the imageUrl to set
	 */
	public void setImageUrl(String imageUrl) {
		this.imageUrl = imageUrl;
	}


	/**
	 * @return the permitWork
	 */
	public boolean isPermitWork() {
		return permitWork;
	}


	/**
	 * @param permitWork the permitWork to set
	 */
	public void setPermitWork(boolean permitWork) {
		this.permitWork = permitWork;
	}

}


